package com.example.mymaijiaxiu;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static android.os.Build.VERSION_CODES.Q;
import static android.os.Environment.MEDIA_MOUNTED;
import static android.os.Environment.MEDIA_MOUNTED_READ_ONLY;
import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private ImageView img;
    private Button btn1,//刷新
    btn2,    //保存
    btn3        //下载更多
            ;
    private Bitmap bitmap;
    private String pic_url;
    private String dir;
    {
        if (Environment.getExternalStorageState().equals(MEDIA_MOUNTED)) {//说明有读写权限
            dir = Environment.getExternalStorageDirectory() + "/tuya/qqq/王者荣耀2.0/";//这个就是外部路径
        }else if (Environment.getExternalStorageState().equals(MEDIA_MOUNTED_READ_ONLY)){
            //则只能读取
        }
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                bitmap= (Bitmap) msg.obj;
                img.setImageBitmap(bitmap);
            } else if (msg.what == 123) {
                ++c;
//                Log.e(TAG, "handleMessage: "+(++c) );
                if (progressDialog != null&&c>=499) {
                    progressDialog.cancel();
                    Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                }else {
                    if (progressDialog != null) {
                        String division = division(c, 500);
                        progressDialog.setMessage("正在下载"+division);
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Window window=getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(this.getResources().getColor(R.color.colorblack));
        init();
        getImg();
    }

    private void init() {
        verifyStoragePermissions(this);//获取存储权限
        img=findViewById(R.id.img);
        btn1 =findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
        btn2=findViewById(R.id.btn2);
        btn2.setOnClickListener(this);
        btn3=findViewById(R.id.btn3);
        btn3.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn1:
                getImg();
                break;
            case R.id.btn2:
                if (bitmap == null) {
                    return;
                }
                downImg();
                break;
            case R.id.btn3:
                downMoreImg();
                break;
        }
    }
    private ProgressDialog progressDialog;
    int c=0;
    private void downMoreImg() {
        c=0;
        progressDialog = new ProgressDialog(this);
//        progressDialog.setCancelable(false);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("由于api接口限制了请求的速度，请耐心等待...预计可以下载300张");
        progressDialog.show();
            final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,15,60,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(500));
            for (int i = 0; i < 500; i++) {
                threadPoolExecutor.execute(new Task());
            }
            threadPoolExecutor.shutdown();
    }

    private void getImg(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String baseURL = "https://api.66mz8.com/api/rand.tbimg.php?format=json";
                try {
                    URL url = new URL(baseURL);
                    URLConnection urlConnection=url.openConnection();
                    HttpURLConnection httpURLConnection= (HttpURLConnection) urlConnection;
                    //设置请求方法 get  post
                    httpURLConnection.setRequestMethod("GET");
                    //设置链接超时时间
                    httpURLConnection.setConnectTimeout(5000);
                    //设置读取超时时间
                    httpURLConnection.setReadTimeout(5000);
                    //返回输入流
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String strbuf=bufferedReader.readLine();
                    String s;
                    while ((s = bufferedReader.readLine())!=null) {
                        strbuf+="\n"+s;
                    }
                    inputStream.close();
                    JSONObject jsonObject = new JSONObject(strbuf);
                    if (jsonObject.getString("code").equals("200")) {
                        pic_url = jsonObject.getString("pic_url");
                        URL url1=new URL(pic_url);
                        URLConnection urlConnection1 = url1.openConnection();
                        HttpURLConnection httpURLConnection1= (HttpURLConnection) urlConnection1;
                        int responseCode = httpURLConnection1.getResponseCode();
                        if (responseCode == 200) {
                            InputStream inputStream1 = httpURLConnection1.getInputStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(inputStream1);
                            inputStream1.close();
                            Message message=new Message();
                            message.what=0;
                            message.obj=bitmap;
                            handler.sendMessage(message);
                        }else {
                            Toast.makeText(MainActivity.this, "加载图片失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    synchronized private void downImg(){
//        String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tuya/qqq/王者荣耀/";//这个就是外部路径
        String filename = pic_url.replace("/", "").replace(":", "").replace(".jpg","").replace("http","").replace(".","").replace("a","").replace("b","").replace("c","").replace("d","").replace("e","").replace("f","").replace("g","").replace("h","").replace("i","").replace("j","").replace("k","").replace("l","").replace("m","").replace("!","").replace("_","").replace("-","").replace("r","").replace("t","").replace("0","").replace("TB","").replace("s","").replace("w","").replace("n","").replace("u","").replace("oo","");
        if (Build.VERSION.SDK_INT<Q){
            //用图片的网络地址来给文件命名
            try {
                File file1=new File(dir+filename+".jpg");
                File file2=new File(dir);
                if (!file2.exists()) {
                    file2.mkdirs();
                }
                if (!file1.exists()){
                    FileOutputStream fileOutputStream = new FileOutputStream(file1);
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    Uri uri = Uri.fromFile(file1);
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            boolean b = saveImage(getApplicationContext(), filename, "王者荣耀2.0");
            if (b) {
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class Task implements Runnable{

        @Override
        public void run() {
            String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tuya/qqq/王者荣耀/";//这个就是外部路径
            String baseURL = "https://api.66mz8.com/api/rand.tbimg.php?format=json";
            try {
                URL url = new URL(baseURL);
                URLConnection urlConnection=url.openConnection();
                HttpURLConnection httpURLConnection= (HttpURLConnection) urlConnection;
                //设置请求方法 get  post
                httpURLConnection.setRequestMethod("GET");
                //设置链接超时时间
                httpURLConnection.setConnectTimeout(5000);
                //设置读取超时时间
                httpURLConnection.setReadTimeout(5000);
                //返回输入流
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String strbuf=bufferedReader.readLine();
                String s;
                while ((s = bufferedReader.readLine())!=null) {
                    strbuf+="\n"+s;
                }
                inputStream.close();
                JSONObject jsonObject = new JSONObject(strbuf);
                if (jsonObject.getString("code").equals("200")) {
                    String pic_url = jsonObject.getString("pic_url");
                    URL url1=new URL(pic_url);
                    URLConnection urlConnection1 = url1.openConnection();
                    HttpURLConnection httpURLConnection1= (HttpURLConnection) urlConnection1;
                    int responseCode = httpURLConnection1.getResponseCode();
                    if (responseCode == 200) {
                        InputStream inputStream1 = httpURLConnection1.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream1);
                        String filename = pic_url.replace("/", "").replace(":", "").replace(".jpg","").replace("http","").replace(".","").replace("a","").replace("b","").replace("c","").replace("d","").replace("e","").replace("f","").replace("g","").replace("h","").replace("i","").replace("j","").replace("k","").replace("l","").replace("m","").replace("!","").replace("_","").replace("-","").replace("r","").replace("t","").replace("0","").replace("TB","").replace("s","").replace("w","").replace("n","").replace("u","").replace("oo","")+".jpg";
                        if (Build.VERSION.SDK_INT<Q){
                            //用图片的网络地址来给文件命名
                            try {
                                File file1=new File(dir+filename);
                                File file2=new File(dir);
                                if (!file2.exists()) {
                                    file2.mkdirs();
                                }
                                if (!file1.exists()){
                                    FileOutputStream fileOutputStream = new FileOutputStream(file1);
                                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
                                    fileOutputStream.flush();
                                    fileOutputStream.close();
                                    Uri uri = Uri.fromFile(file1);
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }else {
                            saveImage(getApplicationContext(),filename,"王者荣耀2.0",bitmap);
                        }
                        inputStream1.close();
                        bitmap.recycle();
                    }else {
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }finally {
                handler.sendEmptyMessage(123);
            }
        }
    }


    public  boolean saveImage(Context context, String fileName, String Subfolders,Bitmap bitmap){
        ContentResolver contentResolver = context.getContentResolver();
        Uri contentUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME,fileName);//文件名
        contentValues.put(MediaStore.Images.Media.MIME_TYPE,"image/*");//文件类型
        if (Subfolders == null) {
            Subfolders="";
        }
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH,"Pictures/"+Subfolders);
        Uri insert = contentResolver.insert(contentUri, contentValues);
        if (insert == null) {
            Log.e("TAG", "onResponse: 异常");
            return false;
        }
        OutputStream outputStream = null;
        try {
            outputStream = contentResolver.openOutputStream(insert);//写入图片的流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
        try {
            outputStream.flush();
            outputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return true;
    }

    public  boolean saveImage(Context context, String fileName, String Subfolders){
        ContentResolver contentResolver = context.getContentResolver();
        Uri contentUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME,fileName);//文件名
        contentValues.put(MediaStore.Images.Media.MIME_TYPE,"image/*");//文件类型
        if (Subfolders == null) {
            Subfolders="";
        }
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH,"Pictures/"+Subfolders);
        Uri insert = contentResolver.insert(contentUri, contentValues);
        if (insert == null) {
            Log.e("TAG", "onResponse: 异常");
            return false;
        }
        OutputStream outputStream = null;
        try {
            outputStream = contentResolver.openOutputStream(insert);//写入图片的流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
        try {
            outputStream.flush();
            outputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return true;
    }




    //先定义
    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };

    //然后通过一个函数来申请
    public static void verifyStoragePermissions(Activity activity) {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 占比计算保留小数的位数方法
     * 转成百分数
     * 当前数除以总数
     * @param  num1 ,num2  num1/num2
     * @return  rate  保留2位小数的
     */
    public static String  division(int num1,int num2){
        String rate="0.0%";
        //定义格式化起始位数
        String format="0.0";
        if(num2 != 0 && num1 != 0){
            DecimalFormat dec = new DecimalFormat(format);
            rate =  dec.format((double) num1 / num2*100)+"%";
            while(true){
                if(rate.equals(format+"%")){
                    format=format+"0";
                    DecimalFormat dec1 = new DecimalFormat(format);
                    rate =  dec1.format((double) num1 / num2*100)+"%";
                }else {
                    break;
                }
            }
        }else if(num1 != 0 && num2 == 0){
            rate = "100%";
        }
        return rate;
    }
}
